import {
  Controller,
  Get,
  Post,
  Body,
  Inject,
  Res,
  ValidationPipe,
  Query,
  UnauthorizedException,
  Req,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { UserService } from './user.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { JwtService } from '@nestjs/jwt';
import { Request, Response } from 'express';
import { RequireLogin, RequirePermission } from 'src/custom-decorator';
import { PaginationDto } from 'src/pagination/dto/pagination.dto';
import { FilesInterceptor } from '@nestjs/platform-express';
import { CursorPaginationDto } from 'src/pagination/dto/cursorPagination.dto';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Inject(JwtService)
  private jwtService: JwtService;

  @Post('login')
  async login(
    @Body() loginDto: LoginDto,
    @Res({ passthrough: true }) res: Response,
  ) {
    const foundUser = await this.userService.login(loginDto);

    // 使用 JWT 生成 token
    if (foundUser) {
      // 创建 access_token，过期时间 30 分钟
      const access_token = await this.jwtService.signAsync(
        {
          user: {
            id: foundUser.id,
            username: foundUser.username,
            roles: foundUser.roles,
          },
        },
        {
          expiresIn: '30m',
        },
      );

      // 创建 refresh_token，过期时间 7 天
      const refresh_token = await this.jwtService.signAsync(
        {
          user: {
            id: foundUser.id,
            username: foundUser.username,
          },
        },
        {
          expiresIn: '7d',
        },
      );

      return {
        access_token,
        refresh_token,
      };
    } else {
      return 'Login failed';
    }
  }

  @Post('register')
  async register(@Body(ValidationPipe) registerDto: RegisterDto) {
    return await this.userService.register(registerDto);
  }

  @Get('userInfo')
  @RequireLogin()
  async userInfo(@Req() req: Request) {
    return this.userService.getUserById(req.user.id);
  }

  @Post('refreshToken')
  async refreshToken(@Body('refreshToken') refreshToken: string) {
    try {
      const payload = await this.jwtService.verifyAsync(refreshToken);
      const user = await this.userService.getUserById(payload.user.id);
      console.log(payload, user);
      const access_token = await this.jwtService.signAsync(
        {
          user: {
            id: user.id,
            username: user.username,
          },
        },
        {
          expiresIn: '30m',
        },
      );

      const refresh_token = await this.jwtService.signAsync(
        {
          user: {
            id: user.id,
            username: user.username,
          },
        },
        {
          expiresIn: '7d',
        },
      );

      return {
        access_token,
        refresh_token,
      };
    } catch (error) {
      throw new UnauthorizedException('token 已失效，请重新登录');
    }
  }

  // 生成权限测试数据
  @Get('init')
  async init() {
    await this.userService.initData();
    return 'done';
  }

  // 权限测试
  @Get('permission_test')
  @RequireLogin()
  @RequirePermission('查询 aaa')
  test() {
    return 'test';
  }

  // 分页测试
  @Get('all')
  async allUser(@Query(ValidationPipe) paginationDto: PaginationDto) {
    return this.userService.allUser(paginationDto);
  }

  // 游标分页测试
  @Get('allByCursor')
  async allUserByCursor(
    @Query(ValidationPipe) paginationDto: CursorPaginationDto,
  ) {
    return this.userService.allUserByCursor(paginationDto);
  }
}
